<template>
    <body-page>
      <div class="body-page-edit">
        <el-form :model="formData" :rules="rules" ref="form" label-width="120px" class="edit-form">

          <el-form-item label="新密码" prop="newPassword" >
              <el-input v-model="formData.newPassword"  type="password"></el-input>
          </el-form-item>

          <el-form-item label="确认新密码" prop="newPasswordRe">
              <el-input v-model="formData.newPasswordRe" type="password"></el-input>
          </el-form-item>

          <el-form-item>
              <el-button type="primary" @click="handleSubmit('form')">确定</el-button>
              <el-button @click="handleReset('form')">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </body-page>
</template>

<script>
import BodyPage from '../../components/BodyPage'
export default {
  name: 'ResetPassword',
  components: {BodyPage},
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formData.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        code: '',
        newPassword: '',
        newPasswordRe: ''
      },
      rules: {
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'}
        ],
        newPasswordRe: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    cancel () {
      this.$router.back()
    },
    handleSubmit (form) {
      let vm = this
      vm.$refs[form].validate((valid) => {
        if (valid) {
          vm.$axios.post(vm.$API.user.passwordReset, vm.$qs.stringify(vm.formData)).then(response => {
            if (response.data.code === 2000) {
              vm.$message.success(response.data.message)
              vm.cancel()
            } else {
              vm.$message.error(response.data.message)
            }
          }).catch(response => {
            console.log(response)
            vm.$message.error('系统异常')
          })
        }
      })
    },
    handleReset (form) {
      this.$refs[form].resetFields()
    }
  },
  created () {
    this.formData.code = this.$route.query.code
  }
}
</script>

<style scoped>
  .body-page-edit {
    padding-top: 20px;
    padding-bottom: 30px;
    background-color: white;
  }

  .edit-form {
    max-width: 500px;
  }
</style>
